﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Drawing;
using System.Collections;

using System.Runtime.InteropServices;
//using Outlook = Microsoft.Office.Interop.Outlook;

using System.IO;

public partial class admin_MultipleSearchAcc : System.Web.UI.Page
{
    rUser ruser;
    DataSet ds;
    DataSet usuEmployee;
    string where1 = "";
   
    DataSet companies;
    DataSet accounts;
    DataSet products;
    
    protected void Page_Load(object sender, EventArgs e)
    {
        
        if (Session["userid"] == null)
        {

            Response.Redirect("../Default.aspx");
        }
        
            //mostrarPaginas();

           
            ds = null;
            
            ruser = (rUser)Session["userid"];
        if (! Page.IsPostBack){
            // si viene de singlesearch
            if (Session["masivo"] != null)
            {
                int perfilID = int.Parse(ruser.getPerfilId());
                where1 = (string)Session["wheremsa"];
                RE_GenericBean permi = Utility.getPermisobyRuser(ruser, 1);
                RE_GenericBean permi2 = Utility.getPermisobyRuser(ruser, 6);
                ds = DB.GetOrdersAcc(permi.int64C1, permi2.int64C1, ruser.getAlias(), where1, "", "", 1, perfilID);
                lnk_Assign.Enabled = true;
                Session["masivo"] = null;
               
            }

            gv_multiple.DataSource = ds;
            gv_multiple.DataBind();
          
            
            
            
            permiso();
            restricted();
        }
    }

    private void permiso()
    {
         long permiso = 0;
        rUser user = (rUser)(Session["userid"]);
        if (user != null)
        {
           // permiso = long.Parse(user.getPermisoUser().ToString());
            RE_GenericBean permi = Utility.getPermisobyRuser(user, 18);
            permiso = permi.int64C1;
           
        }
        if ((permiso & 2) != 2)
        {
            lnk_Assign.Visible = false;
        }
    }

    private void restricted()
    {
        long permiso = 0;
        rUser user = (rUser)(Session["userid"]);
        if (user != null)
        {

            RE_GenericBean permi = Utility.getPermisobyRuser(user, 18);
            permiso = permi.int64C2;
        }
        if ((permiso & 1) == 1) { Response.Redirect(Request.UrlReferrer.ToString()); }
    }
    protected void bt_searchgroup_Click(object sender, ImageClickEventArgs e)
    {
        

    }

    protected void gv_multiple_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header)
        {
            //e.Row.Cells[1].Style.Add("display", "none");//ordernum
           // e.Row.Cells[2].Style.Add("display", "none");//statusname
            //e.Row.Cells[9].Style.Add("display", "none");//zip
            //e.Row.Cells[10].Style.Add("display", "none");//orderid
            //e.Row.Cells[12].Style.Add("display", "none");//psfee
        }

        if (e.Row.RowType == DataControlRowType.Header){

 
        
        }
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            TextBox isPaid = (TextBox)e.Row.FindControl("isPaid");
            string paid = isPaid.Text;
            if (paid == "false") {
                e.Row.FindControl("image").Visible = false;
            }
            e.Row.FindControl("isPaid").Visible= false;
         }
           


        
    }

    private int sendMail(string body, string valor)
    {
        int result = 0;
        //buscando email del procesador
        DataSet usuEmployee;
        string mail = "";
        usuEmployee = (DataSet)HttpContext.Current.Session["Usuarios"];
        if (usuEmployee == null)
        {
            setVariablesSession();
        }
        if (usuEmployee != null)
        {
            for (int i = 0; i < usuEmployee.Tables[0].Rows.Count; i++)
            {


                string alias = usuEmployee.Tables["Tabla"].Rows[i]["alias"].ToString().ToUpper().Trim();
                if (alias.Equals(valor.ToUpper().Trim()))
                {
                    mail = usuEmployee.Tables["Tabla"].Rows[i]["email"].ToString().Trim();
                }

            }



            string from = "bpo@bpophotos.com";
            string Subject = "New order Assigned in bpophotos.com";

            /*// string res = Utility.sendMail(from, mail, Subject, body);
             // Create the Outlook application by using inline initialization.
             Outlook.Application oApp = new Outlook.Application();

             //Create the new message by using the simplest approach.
             Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
        

             //Add a recipient.
             // TODO: Change the following recipient where appropriate.
             Outlook.Recipient oRecip = (Outlook.Recipient)oMsg.Recipients.Add(mail);
     
             oRecip.Resolve();

             //Set the basic properties.
             oMsg.Subject = Subject;
             //oMsg.Body = body;
             oMsg.HTMLBody = body;

             //Add an attachment.
             /*TODO: change file path where appropriate
             String sSource = "C:\\setupxlg.txt";
             String sDisplayName = "MyFirstAttachment";
             int iPosition = (int)oMsg.Body.Length + 1;
             int iAttachType = (int)Outlook.OlAttachmentType.olByValue;  
             Outlook.Attachment oAttach = oMsg.Attachments.Add(sSource,iAttachType,iPosition,sDisplayName);
         */
            /*   // If you want to, display the message.
               oMsg.Display(true);  //modal

               //Send the message.
               //oMsg.Save();
               //oMsg.Send();

               //Explicitly release objects.
               oRecip = null;
               //oAttach = null;
               oMsg = null;
               oApp = null;*/

            result = 1;
        }
        return result;         
    }
    protected void lnk_search_Click(object sender, EventArgs e)
    {
        string ordersgroup = tb_orders.Text.Trim();

        ordersgroup = ordersgroup.Replace(",", "','");
        ordersgroup = "'" + ordersgroup + "'";
        ordersgroup = " WHERE  [ORDER].ordernum in (" + ordersgroup + ")";
        if (!cb_msubmitted.SelectedValue.Equals("All"))
        {

            if (cb_msubmitted.SelectedValue.ToUpper().Equals("NO"))
            {
                ordersgroup = ordersgroup + " and ([ORDER].status_id <> 3 )";
            }
            else
            {
                ordersgroup = ordersgroup + " and [ORDER].status_id = 3 ";
            }

        }
        else {
            ordersgroup = ordersgroup + " and ([ORDER].status_id = 3 or [ORDER].status_id = 4 or [ORDER].status_id = 5)";
        
        }
        Session["masivo"] = ordersgroup;
        Session["wheremsa"] = ordersgroup;
        Response.Redirect("MultipleSearchAcc.aspx");
    }

    protected void lnk_Assign_Click(object sender, EventArgs e)
    {
        
        setVariablesSession();
        lb_error.Visible = false; lb_mensaje.Visible = false;
        string ordersgroup = ""; int p = 0; int pos = 0;
        string[] orders = new string[100];
        ArrayList array = new ArrayList();
        foreach (GridViewRow ROW in gv_multiple.Rows)
        {

            string ordernum = ""; string fee = "0";
            
            CheckBox chk = (CheckBox)ROW.FindControl("CHBX1");
            if (chk.Checked)
            {
                Label label = (Label)ROW.FindControl("lb_order");
                if (label!= null){ordernum= label.Text;}

            }
            TextBox txt = (TextBox)ROW.FindControl("tbx_fee");
            if (!txt.Text.Equals("")) {
                fee = txt.Text;
            }

            RE_GenericBean rg = new RE_GenericBean();
            rg.strC1 = ordernum;
            rg.strC2 = fee;
            array.Add(rg);
        }

                ruser = (rUser)Session["userid"];
                RE_GenericBean resop = DB.setPaid(array, ruser.getUsuarioId());
                if (resop.intC1 == 1)
                {
                    lb_mensaje.Text = "Paid Set";
                    lb_mensaje.Visible = true;
                }
                else {
                    lb_error.Text = "Paid not Set";
                    lb_error.Visible = true;
                }
             
        
        
        
        where1 = (string)Session["wheremsa"];
        int perfilID = int.Parse(ruser.getPerfilId());
         RE_GenericBean permi = Utility.getPermisobyRuser(ruser, 1);
         RE_GenericBean permi2 = Utility.getPermisobyRuser(ruser, 6);
         perfilID = int.Parse(ruser.getPerfilId());
        ds = DB.GetOrdersAcc(permi.int64C1, permi2.int64C1, ruser.getAlias(), where1, "","",0,perfilID);
        gv_multiple.DataSource = ds;
        gv_multiple.DataBind();
        //Response.Write("<script type='text/javascript'>window.open('changeGroup.aspx?get="+ordersgroup+"','cal','width=600,height=350,left=100,top=100,scrollbars=NO,resizable=NO');</script>"); 
    }

    

    private void setVariablesSession()
    {
        string rxmlcompanies = null;
        DataSet usuGeneral;
        com.bpophotos.www.Service service = new com.bpophotos.www.Service();
       

        try
        {
            companies = (DataSet)Session["companies"];
            accounts = (DataSet)Session["accounts"];
            products = (DataSet)Session["products"];
            usuEmployee= (DataSet)Session["Usuarios"];
            if (products == null) { products = (DataSet)DB.GetProducts(); }
            if (companies == null){rxmlcompanies = service.getCompanies();
            companies = Utility.getCompanies(rxmlcompanies);}
            if (accounts == null){
                 string xmlaccount = service.getAccounts();
                accounts = Utility.getAccounts(xmlaccount);
            }
            if (usuEmployee== null){
                string rxml1 = service.getPerfiles(1,1);
                DataSet perfiles = Utility.getPerfiles(rxml1);
                Session["Perfiles"] = perfiles;
                // Utility.writeError("Error Default " + rxml1);
                usuEmployee = Utility.getTodosUsuarios(rxml1);
            }
            
            Session["companies"]= companies;
            Session["accounts"] = accounts;
            Session["products"] = products;
            Session["Usuarios"] = usuEmployee;
           

        }
        catch (Exception ex) { Utility.writeError(ex.Message); }
        finally
        {
            if (service != null) { service.Dispose(); }

        }
    }


    private void CreateEmailMessage(string strTo, string strSubject, string strCC, string strBody)
    {
        try
        {
            // Create the Outlook application by using inline initialization.
            /*Outlook.Application oApp = new Outlook.Application();

            //Create the new message by using the simplest approach.
            Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

            //Add a recipient.
            // TODO: Change the following recipient where appropriate.
            Outlook.Recipient oRecip = (Outlook.Recipient)oMsg.Recipients.Add("e-mail address");
            oRecip.Resolve();

            //Set the basic properties.
            oMsg.Subject = "This is the subject of the test message";
            oMsg.Body = ".";

            //Add an attachment.
            /*TODO: change file path where appropriate
            String sSource = "C:\\setupxlg.txt";
            String sDisplayName = "MyFirstAttachment";
            int iPosition = (int)oMsg.Body.Length + 1;
            int iAttachType = (int)Outlook.OlAttachmentType.olByValue;  
            Outlook.Attachment oAttach = oMsg.Attachments.Add(sSource,iAttachType,iPosition,sDisplayName);
        */
            // If you want to, display the message.
        /*    oMsg.Display(true);  //modal

            //Send the message.
            //oMsg.Save();
            //oMsg.Send();

            //Explicitly release objects.
            oRecip = null;
            //oAttach = null;
            oMsg = null;
            oApp = null;*/
        }

               // Simple error handler.
        catch (Exception ex)
        {
            Response.Write("<script> alert('Email Fail ');</script>");
        }




    }
    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {

        foreach (GridViewRow ROW in gv_multiple.Rows)
        {


            CheckBox chk = (CheckBox)ROW.FindControl("CHBX1");
            if (CheckBox1.Checked)
            {
                chk.Checked = true;
            }
            else {
                chk.Checked = false;
            }

        }
    }
    protected void lnk_add_bank_Click(object sender, EventArgs e)
    {

    }
    protected void lnk_edit_Click(object sender, EventArgs e)
    {
        
    }
}